<template>
  <div class="home">
    <!-- 顶部导航栏 -->
    <NavBar title="" :showPlaceholder="false">
      <template #right>
        <RouterLink :to="{ name: 'SearchPage' }">
          <Icon name="search" color="#fff" />
        </RouterLink>
      </template>
    </NavBar>

    <!-- 视频轮播 -->
    <Swipe v-if="videoList?.length" :key="videoList.length" :height="667" :showIndicators="false"
      @change="handleSwipeChange">
      <SwipeItem v-for="(item, index) in videoList" :key="item.Video?.userId || index">
        <!-- 视频播放器 -->
        <CustomVideo :ref="el => videoRefs[index] = el" :src="item.Video?.videoPath" :active="currentIndex === index"
          @dbltap="handleDoubleTap(index)" :poster="getPoster(item)" />

        <!-- 左侧：视频信息 -->
        <template #left>
          <div class="video_intro">
            <div class="video_intro__city">北京市</div>
            <div class="video_intro__username">@{{ item.Video?.userNickname }}</div>
            <div class="video_intro__desc">{{ item.Video?.videoDesc }}</div>
          </div>
        </template>

        <!-- 右侧：操作按钮 -->
        <template #right>
          <div class="video_operation">
            <!-- 用户头像 -->
            <div class="video_operation__item" @click="handleUserDetail(item.Video?.userId)">
              <img :src="item.Video?.userAvatar ? 'http://43.138.15.137:3000' + item.Video.userAvatar : ''" alt="" />
              <Icon class="jia-icon" name="jia" size="20" color="#fff" />
            </div>

            <!-- 点赞 -->
            <div class="video_operation__item" @click="handleLike(item, index)">
              <div class="like-wrapper" :class="{ animated: item.animated }">
                <Icon name="xin-2" size="32" :color="isLiked(item.WSLCNum.likeList) ? '#ff0000' : '#fff'" />
              </div>
              <span>{{ item.WSLCNum.likeNum }}</span>
            </div>

            <!-- 评论 -->
            <div class="video_operation__item" @click="handleComment(item.Video?.videoId, index)">
              <Icon name="pinglun" size="32" color="#fff" />
              <span>{{ item.WSLCNum.commentNum }}</span>
            </div>

            <!-- 分享 -->
            <div class="video_operation__item">
              <Icon name="a-fenxiangweifenxiang" size="24" color="#fff" />
              <span>{{ item.WSLCNum.shareNum }}</span>
            </div>
          </div>
        </template>
      </SwipeItem>
    </Swipe>

    <!-- 评论弹窗 -->
    <Commentcomponent v-model="isShowComment" :commentList="commentList" @newComment="handleNewComment"
      :videoId="currentVideoId" />
  </div>

  <!-- 登录组件（从下往上过渡） -->
  <transition name="fade-down">
    <LoginComponent v-if="userStore.showLoginComponent" />
  </transition>
</template>

<script setup>
import { onMounted, ref, defineAsyncComponent, defineOptions, onActivated, onDeactivated, nextTick } from 'vue'

import { useUserStore } from '@/stores/userStatus'
import { useUserIDStore } from '@/stores/UserID'
import {
  getHomeVideoListAPI,
  likeAPI,
  commentAPI,
  commentLikeAPI
} from '@/api/Home'


// 显示 


// ----------------------------

// 组件导入
// ----------------------------
import Swipe from '@/components/Common/Swipe/index.vue'
import SwipeItem from '@/components/Common/SwipeItem/index.vue'
import NavBar from '@/components/Common/NavBar/index.vue'
import Icon from '@/components/Common/Icon/index.vue'
import CustomVideo from '@/components/Common/CustomVideo/index.vue'

const Commentcomponent = defineAsyncComponent(() =>
  import('@/views/home/Commentcomponent/index.vue')
)
const LoginComponent = defineAsyncComponent(() =>
  import('@/views/home/LoginComponent/index.vue')
)
// 定义 ref 数组
const videoRefs = ref([])
// 激活时恢复播放
onActivated(() => {
  nextTick(() => {
    const currentVideo = videoRefs.value[currentIndex.value]
    if (currentVideo && typeof currentVideo.play === 'function') {
      // 尝试播放（静音，应该能成功）
      currentVideo.play()
    }
  })
})

// 离开时暂停（可选，节省资源）
onDeactivated(() => {
  const currentVideo = videoRefs.value[currentIndex.value]
  if (currentVideo && typeof currentVideo.pause === 'function') {
    currentVideo.pause()
  }
})
defineOptions({
  name: 'home'
})

// ----------------------------
// 状态与数据
// ----------------------------
const userStore = useUserStore()
const userIDStore = useUserIDStore()

const videoList = ref([])
const currentIndex = ref(0)
const isShowComment = ref(false)
const commentList = ref([])
const currentVideoId = ref(null)

// ----------------------------
// 工具函数
// ----------------------------
/**
 * 判断当前用户是否已点赞
 */
const isLiked = (likeList) => {
  const currentUserId = userStore.userInfo?.userId || 1
  return Array.isArray(likeList) && likeList.includes(currentUserId)
}

// ----------------------------
// 事件处理
// ----------------------------
/**
 * 轮播切换
 */
const handleSwipeChange = (index) => {
  currentIndex.value = index
}

/**
 * 双击点赞
 */
const handleDoubleTap = (index) => {
  const item = videoList.value[index]
  if (item?.Video) handleLike(item, index)
}

/**
 * 点赞逻辑（点击/双击共用）
 */
const handleLike = async (item, index) => {
  // 未登录则弹出登录框
  if (!userStore.isLogin) {
    userStore.showLoginComponent = true
    return
  }

  const { Video, WSLCNum, isLiking } = item
  if (!Video || isLiking) return

  // 防抖锁
  item.isLiking = true

  const currentUserId = userStore.userInfo?.userId || 1
  const wasLiked = isLiked(WSLCNum.likeList)

  // 1. 本地立即更新 UI
  if (wasLiked) {
    WSLCNum.likeList = WSLCNum.likeList.filter(id => id !== currentUserId)
    WSLCNum.likeNum--
  } else {
    WSLCNum.likeList.push(currentUserId)
    WSLCNum.likeNum++
  }

  // 2. 播放动画
  item.animated = true
  setTimeout(() => (item.animated = false), 600)

  // 3. 发送请求
  try {
    await likeAPI(Video.userId, Video.videoId)
  } catch (error) {
    console.error('点赞失败，回滚 UI')
    // 回滚
    if (wasLiked) {
      WSLCNum.likeList.push(currentUserId)
      WSLCNum.likeNum++
    } else {
      WSLCNum.likeList = WSLCNum.likeList.filter(id => id !== currentUserId)
      WSLCNum.likeNum--
    }
  } finally {
    // 防抖释放（加一点容错）
    setTimeout(() => {
      if (item.isLiking) item.isLiking = false
    }, 800)
  }
}

/**
 * 打开评论弹窗
 */
const handleComment = async (videoId, index) => {
  if (!userStore.isLogin) {
    userStore.openLoginModal()
    return
  }
  if (!videoId || index === undefined) return

  currentVideoId.value = videoId

  try {
    const res = await commentAPI(videoId)
    if (res.code !== 200) return

    // 保留原始时间戳
    commentList.value = res.data.map(item => ({
      ...item,
      Comment: {
        ...item.Comment,
        createdAt: item.Comment.createdAt
      }
    }))

    // 获取每条评论的点赞状态
    const userId = userIDStore.userInfo?.userId
    if (userId) {
      for (const item of commentList.value) {
        const likeRes = await commentLikeAPI(userId, item.Comment.commentId)
        if (likeRes.code === 200) {
          item.Comment.isLiked = likeRes.data
        }
      }
    }

    isShowComment.value = true
  } catch (error) {
    console.error('获取评论失败:', error)
  }
}

/**
 * 新增评论后更新列表
 */
const handleNewComment = (newComment) => {
  commentList.value.unshift(newComment)
}

// ----------------------------
// 生命周期
// ----------------------------
/**
 * 初始化加载视频列表
 */
const getVideoAPI = async () => {
  try {
    const res = await getHomeVideoListAPI()
    videoList.value = res.data
      .map(item => {
        try {
          const parsed = JSON.parse(item)
          parsed.WSLCNum = {
            likeNum: parsed.WSLCNum?.likeNum || 0,
            commentNum: parsed.WSLCNum?.commentNum || 0,
            shareNum: parsed.WSLCNum?.shareNum || 0,
            likeList: parsed.WSLCNum?.likeList || []
          }
          parsed.animated = false
          parsed.isLiking = false
          return parsed
        } catch (err) {
          console.error('JSON 解析失败:', item, err)
          return null
        }
      })
      .filter(Boolean)

    // ✅ 关键：等待 DOM 渲染完成后再操作 videoRefs
    await nextTick()

    // 预加载首屏视频（index = 0）
    const firstVideoRef = videoRefs.value[0]
    if (firstVideoRef?.element?.value) {
      const videoEl = firstVideoRef.element.value
      console.log(videoEl)

      // 1. 确保 muted（否则 autoplay 会被浏览器阻止）
      videoEl.muted = true
      videoEl.playsInline = true

      // 2. 触发加载
      videoEl.load()

      // 3. 尝试静音播放（触发解码和缓冲）
      videoEl.play().catch(err => {
        console.warn('首屏视频预播放被阻止（正常）:', err)
        // 即使失败也没关系，load() 已触发缓冲
      })
    }
  } catch (error) {
    console.error('获取视频列表失败:', error)
  }
}

onMounted(() => {
  getVideoAPI()
})
/**
 * 获取视频封面：优先用 videoCover（未来可扩展），其次 userAvatar，最后默认图
 */
const getPoster = (item) => {
  // 如果后端未来支持 videoCover，可以放开下面这行
  // if (item.Video?.videoCover) return 'http://43.138.15.137:3000' + item.Video.videoCover

  // 当前用用户头像作为封面（需拼接 base URL）
  if (item.Video?.userAvatar) {
    return 'http://43.138.15.137:3000' + item.Video.userAvatar
  }

  // 最终 fallback：默认占位图（建议放一个 720x1280 的纯色或 logo 图）
  return '/images/default-video-poster.jpg'
}
// 跳转用户详情页
import { useRouter } from 'vue-router'
const router = useRouter()
const handleUserDetail = (friendId) => {
  router.push({
    name: 'UserDetails',
    params: { friendId },
    query: { from: 'home' } // 添加来源标识
  })
}
</script>

<style lang="scss" scoped>
.home {
  position: relative;
  width: 100%;
  height: 100vh;
  background-color: #000;
  overflow: hidden;
}

.fade-down-enter-active,
.fade-down-leave-active {
  transition: all 0.6s ease;
}

.fade-down-enter-from,
.fade-down-leave-to {
  transform: translateY(100%);
  opacity: 0;
}
</style>